package com.atguigu.book.controller;

import com.atguigu.book.pojo.Book;
import com.atguigu.book.pojo.Cart;
import com.atguigu.book.pojo.CartItem;
import com.atguigu.book.pojo.User;
import com.atguigu.book.service.CartItemService;

import javax.servlet.http.HttpSession;

/**
 * @ClassName: CartItemController
 * @Description:
 * @Author: wty
 * @Date: 2022/12/13
 */

public class CartItemController {
    private CartItemService cartItemService;

    /**
     * @param
     * @return java.lang.String
     * @description 将指定的图书添加到当前用户的购物车中
     * 1.如果当前用户的购物车中已经存在这个图书了，那么将购物车中这本图书的数量+1
     * 2.否则，在我的购物车中新增一个这本图书的CartItem，数量是1
     * @param: bookId
     * @date 2022/12/13 14:39
     * @author wty
     **/
    public String addCart(Integer bookId, HttpSession session) {
        User currUser = (User) session.getAttribute("currUser");
        Cart cart = currUser.getCart();

        CartItem cartItem = new CartItem(new Book(bookId), 1, currUser);

        cartItemService.addOrUpdateCartItem(cartItem, cart);

        return "redirect:cart.do";
    }

    /**
     * @param
     * @return java.lang.String
     * @description 加载当前用户的购物车信息
     * @date 2022/12/13 16:33
     * @author wty
     **/
    public String index(HttpSession session) {
        User currUser = (User) session.getAttribute("currUser");

        Cart cart = cartItemService.getCart(currUser);
        currUser.setCart(cart);
        session.setAttribute("currUser", currUser);

        return "cart/cart";
    }

    public String editCart(Integer cartItemId, Integer buyCount) {
        cartItemService.updateCartItemBuyCount(new CartItem(cartItemId, buyCount));
        return "redirect:cart.do";
    }
}
